/**
 * 
 */
package com.tmc.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.tmc.bean.common.ContextInfo;
import com.tmc.service.common.LoginServiceImpl;

@Controller
public class BaseController {
	
	@Autowired
	private LoginServiceImpl login;

	@InitBinder
	protected void ininBinder(WebDataBinder binder){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf,true));
	}
	
	public ContextInfo getContextInfo(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null || cookies.length == 0){
			return null;
		}
		for (Cookie cookie : cookies){
			if ("token".equals(cookie.getName())){
				String token = cookie.getValue();
				return login.getContextInfoByToken(token);
			}
		}
		return null;
	}

	public ContextInfo getContextInfo(String token) {
		return login.getContextInfoByToken(token);
	}

	public void processContext(HttpServletRequest request, Map<String, Object> map) {
		ContextInfo context = this.getContextInfo(request);
		map.put("context", context);
	}
}
